<?php

namespace app\common\service\product;
use app\common\cache\product\ShopProductCache;
use app\common\model\order\ShopOrderModel;
use app\common\model\product\ShopProductEnterModel;
use app\common\model\product\ShopProductGoodsModel;
use app\common\model\product\ShopProductIncrementModel;
use app\common\model\product\ShopProductModel;
use app\common\model\product\ShopProductPriceModel;
use app\common\model\product\ShopProductReleaseModel;
use app\common\model\setting\SettingPriceAttributesModel;
use app\common\model\setting\SettingPriceRangeModel;
use app\common\model\setting\SettingRefundModel;
use app\common\model\setting\SettingStorePlatformModel;
use app\common\service\file\FileService;
use app\common\service\file\MerchantFileService;
use app\common\service\file\SettingService;
use app\common\service\member\MemberService;
use app\common\service\merchant\MerchantService;
use app\common\service\order\ShopOrderService;
use app\common\service\setting\RegionService;
use app\common\service\setting\SettingPriceRangeService;
use app\common\service\setting\SettingRefundService;
use app\common\service\member\SettingService as MemberSettingService;
use app\common\service\system\SettingService as SystemSettingService;
use app\common\service\utils\QrCodeUtils;
use DateTime;
use think\facade\Db;

/**
 * 商品管理
 */
class ShopProductService
{
    private static $time_on;
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id'=>null,//主键ID
        'title/s'=>null,//标题
        'content/s'=>null,//内容
        'store_platform_id/d'=>null,//店铺平台ID
        'merchant_id/d'=>null,//商家ID
        'merchant_shop_id/d'=>null,//店铺ID
        'setting_refund_id/d'=>null,//返款类型【平台补贴、商家返款】
        'shop_product_type_id/d'=>null,//活动类型【平台补贴、垫付任务、浏览任务】
        'shop_product_type_code/s'=>null,//活动类型编码
        'status/d'=>0,//状态：（0、待付款  1、待审核  2、进行中  3、完成 4、审核未通过 5、已撤销 5、已暂停 6、已删除）
        'money/f'=>0,//总金额
        'remark/s'=>null,//备注内容
        'b_is_delivery/d'=>1,//是否包邮:0、否 1、是
        'b_delivery_price/f'=>0,//运费
        'b_coupon_url/s'=>null,//优惠券链接(暂无用)
        'b_coupon_price/f'=>0,//优惠券金额(暂无用)
        'c_sort_type/d'=>0,//排序方式：0、综合  1、销量  2、直通车
        'c_pay_num/d'=>0,//付款人数
        'c_start_price/f'=>0,//价格区间起
        'c_end_price/f'=>0,//价格区间止
        'c_region_id/d'=>null,//商品所在地
        'c_order_remark/s'=>null,//下单备注
        'c_subject/s'=>null,//宝贝详情问答(2~10个字)
        'd_enter_type/d'=>null,//进店方关式：0、关键词  1、口令 2、二维码 3、链接(暂无用，进子表)
        'e_revoke_time/d'=>24,//自动撤销（小时）默认24
        'e_time_type/d'=>0,//放单时间类型：0、间隔模式 1、时间段模式
        'f_auth_type/d'=>0,//审核方式：0、商家自行审核淘宝号  1、 旺旺照妖镜验号(0.2金/单)(暂无用)
        'f_reward_price/f'=>0,//加赏任务佣金/单(暂无用)
        'h_pay_time'=>null,//支付时间
        'h_pay_type/d'=>0,//支付状态：0、未支付 1、余额支付 2、在线支付
        'sort/d'=>255,//排序
        'order_num/d'=>0,//总订单数
        'f_increment_num/d'=>0,//增值项目数量
        'f_increment_price/f'=>0,//增值项目金额
        'd_comment_num/d'=>0,//好评项目数量
        'd_comment_price/f'=>0,//好评项目金额
        'b_product_num/d'=>0,//商品数量
        'b_product_price/f'=>0,//商品下单总金额
        'is_top/d'=>0,//是否置顶，1是0否
    ];

    /**
     * 查询列表页所需参数
     * @Author: 易军辉
     * @DateTime:2024-06-07 17:26
     * @param $where
     * @param $order
     * @param $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getListParams()
    {
        $platform_list = Db::name('setting_store_platform')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('id as value,title as label')
            ->select();
        //查询活动分类
        $product_types = Db::name('shop_product_type')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('id as value,title as label')
            ->select();
        //查询返款类型
        $refund_list = Db::name('setting_refund')
            ->where('is_delete',0)
            ->field('id as value,title as label')
            ->select();
        //查询店铺
        $merchantId = mer_id();
        $shop_list = Db::name('merchant_shop')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('auth_status',1)
            ->field('id as value,title as label')
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })
            ->select();
        //查询订单状态
        $order_status = ShopOrderModel::STATUS;
//        foreach ($order_status as $key=>$val){
//            if($val['code'] == 'o_stop'){
//                unset($order_status[$key]);
//                break;
//            }
//        }
        return compact('platform_list','product_types','refund_list','shop_list','order_status');
    }

    /**
     * 查询发布商品时所需参数
     * @param $where 条件
     * @return array
     */
    public static function getParams($where = [],$order = [], $field = '')
    {
        $mer_id = mer_id();
        //商家活动分类id
        $product_type_ids = Db::name('merchant')->where('id',$mer_id)->value('shop_product_type_ids');
        if($product_type_ids){
            $product_type_ids = explode(',',$product_type_ids);
        }else{
            $product_type_ids = [];
        }
        //查询店铺平台、活动分类、商家店铺
        $model = new SettingStorePlatformModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,title,code,image_id,service_money,sort,remark';
        }
        if (empty($order)) {
            $order = ['sort'=>'asc',$pk => 'desc'];
        }
        $with     = [
            'merchantShop'=>function ($query)use($mer_id) {
                $query->when($mer_id>0,function($query)use($mer_id){
                    $query->where('merchant_id',$mer_id);
                })->where('is_disable',0)->where('is_delete',0)->where('auth_status',1)->field('id as mer_shop_id,title,setting_store_platform_id,merchant_id,is_disable,is_mer_rebate,setting_store_type_id');
            },
            'productTypes'=>function ($query)use($product_type_ids) {
                $query->order('sort','asc')
                    ->when(count($product_type_ids)>0, function($query) use ($product_type_ids) {
                        $query->where('shop_product_type_id','in',$product_type_ids);
                    })
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->with('image');
            },
        ];
        $append = $hidden = [];
        if (strpos($field, 'image_id') !== false) {
            $with[]   = $hidden[] = 'image';
            $append[] = 'image_url';
        }

        $platform_list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        //查询返款类型
        $refund_list = SettingRefundService::list([where_delete()],0,0,[],'id as value,title as label,is_disable as disable,describe,remark,code,price');
        return compact('platform_list','refund_list');
    }
    /**
     * 查询发布商品时所需参数
     * @param $where 条件
     * @return array
     */
    public static function getParams1($where = [],$order = [], $field = '')
    {
        //查询地区
        $region = RegionService::list('tree', [where_delete()], [], 'region_id,region_pid,region_name');
        //查询好评信息
        $comment_where[] = ['is_disable','<>',1];
        $comment_where[] = ['status','=',2];
        $comment_res = SettingPriceRangeService::getPriceRange(where_delete($comment_where));
        $comment_list = $comment_res['result'];
        $comment_types = SettingPriceRangeService::getCommentTypes();
        //查询增值佣金
        $increment_where[] = ['is_disable','<>',1];
        $increment_where[] = ['status','=',1];
        $increment_res = SettingPriceRangeService::getPriceRange(where_delete($increment_where));
        $increment_list = $increment_res['result'];
        $f_increment_values = $increment_res['f_increment_values'];//条件默认值
        //查询基础商品佣金
        $basic_where[] = ['is_disable','<>',1];
        $basic_where[] = ['status','=',0];
        $basic_res = SettingPriceRangeService::getPriceRange(where_delete($basic_where), ['price_close'=>'desc','sort'=>'asc']);
        $basic_list = $basic_res['result'];
        //查询商品分类
        $store_types = Db::name('setting_store_type')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('id as value,title as label')
            ->select();
        return compact('region','comment_list','comment_types','increment_list','f_increment_values','basic_list','store_types');
    }
    /**
     * 商品管理列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $sql = self::getListSql($where,$order,$field);
        if ($page == 0 || $limit == 0) {
            return Db::query($sql);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        //查询图片路径
        foreach ($list as &$item) {
            if($item['platform_image_id']){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $item['platform_image_url'] =$file['file_url'];
                }
            }
            if($item['goods_image_id']){
                $file = MerchantFileService::info($item['goods_image_id']);
                if($file && isset($file['file_url'])){
                    $item['goods_image_url'] =$file['file_url'];
                }
            }
            $item['status_title'] = ShopProductModel::getStatus($item['status'],2);
        }
        $status_nums = self::getStatusNum();
        return compact('count', 'pages', 'page', 'limit', 'list','status_nums');
    }

    /**
     * 查询状态数量
     * @Author: 易军辉
     * @DateTime:2024-06-07 16:55
     */
    public static function getStatusNum(){
        $merchantId = mer_id();
        $where = " where is_disable=0 and is_delete=0";
        if($merchantId>0){
            $where .=" and merchant_id=".$merchantId;
        }
        //根据状态查询数量
        $status_num = Db::query("SELECT status,count(id) as num from ya_shop_product ".$where." GROUP BY status");
        $status_nums = array();

        $status_nums['all'] = Db::name('shop_product')
            ->where('is_delete',0)
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })->count();
        foreach (ShopProductModel::STATUS as $k => $v) {
            $status_nums[$v['code']] =0;
            foreach ($status_num as $k1 => $v1) {
                if($v1['status'] == $v['value']) {
                    $status_nums[$v['code']] = $v1['num'];
                    break;
                }
            }
        }
        return $status_nums;
    }


    /**
     * 组装查询SQL
     * @Author: 易军辉
     * @DateTime:2024-06-07 14:56
     * @param $where
     * @param $order
     * @return string
     */
    private static function getListSql($where = [], $order = [],$field = '')
    {
        /***************************查询字段***********************************************/
        if (empty($field)) {
            $field = 'platform.title as platform_title,
            platform.image_id as platform_image_id,
            type.title as type_title,
            shop.title as shop_title,
            refund.title as refund_title,
            goods.id as goods_id,
            goods.goods_title,
            goods.image_id as goods_image_id,
            goods.goods_spec,
            goods.goods_type,
            goods.third_id as goods_third_id,
            a.id,
            a.merchant_id,
            a.order_num,
            a.money,
            a.principal,
            a.commission,
            a.status,
            a.remark,
            a.create_time,
            a.in_time,
            a.end_time,
            a.b_product_num,
            a.b_product_price,
            a.is_top,
            orders.*';
        }
        $order_field =" shop_product_id";
        foreach (ShopOrderModel::STATUS as $k => $v) {
            if($order_field != ""){
                $order_field .=",";
            }
            $order_field .= ' COUNT(CASE WHEN status = '.$v['value'].' THEN 1 END) as '.$v['code'];
        }
        /***************************组装条件***********************************************/
        $where_sql = "";
        foreach ($where as $key=>$val){
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if($val[0] == 'platform_ids' && isset($val[2])){
                $where_sql .="platform.id in(".implode(',',$val[2]).")";
            }else if($val[0] == 'product_type_ids' && isset($val[2])) {
                $where_sql .= "type.id in(" . implode(',',$val[2]) . ")";
            }else if(is_array($val[2])) {
                $where_sql .= "a." . $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else if($val[0] == 'status' && $val[2]>=0){
                $where_sql .="a.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }else{
                $where_sql .="a.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
        /***************************组装排序***********************************************/
        $order_sql = "";
        foreach ($order as $key=>$val){
            if($order_sql!=""){
                $order_sql .=" , ";
            }
            $order_sql .="a.".$key." ".$val." ";
        }
        if($order_sql == ""){
            $order_sql = "a.status asc,a.id desc";
        }
        $sql = <<<SQL
            SELECT 
                 {$field}
                FROM ya_shop_product AS a
                -- 关联商品表，取第一条商品
                LEFT JOIN (
                    SELECT goods.*,goods_type.title as goods_type 
                    FROM ya_shop_product_goods as goods
                        -- 关联商品分类
                        LEFT JOIN ya_setting_store_type AS goods_type ON goods.setting_store_type_id = goods_type.id
                    WHERE (goods.shop_product_id,goods.id) IN (
                        SELECT shop_product_id, MIN(id) 
                        FROM ya_shop_product_goods 
                        GROUP BY shop_product_id
                    )
                ) AS goods ON a.id = goods.shop_product_id
                -- 关联店铺平台
                LEFT JOIN ya_setting_store_platform AS platform ON a.store_platform_id = platform.id
                -- 关联活动分类	
                LEFT JOIN ya_shop_product_type AS type ON a.shop_product_type_id = type.id
                -- 关联店铺
                LEFT JOIN ya_merchant_shop as shop ON a.merchant_shop_id = shop.id
                -- 关联返款类型
                LEFT JOIN ya_setting_refund as refund ON a.setting_refund_id = refund.id
                -- 关联订单
                LEFT JOIN(
                  SELECT 
                  {$order_field}
                  FROM ya_shop_order GROUP BY shop_product_id
                )as orders ON a.id = orders.shop_product_id
            WHERE
                {$where_sql}
            ORDER BY 
                {$order_sql}
        SQL;
        return $sql;
    }

    /**
     * 商品管理信息
     *
     * @param int  $id   商品管理id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = ShopProductCache::get($id);
        if (empty($info)) {
            $model = new ShopProductModel();
            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('商品管理不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            $merchantId = mer_id();
            /***************************************查询商品信息***********************************************************/
            $shop_product_goods = Db::name('shop_product_goods')->where(['shop_product_id' => $info['id']])->select()->toArray();
            foreach ($shop_product_goods as $key=>$val){
                if($val['image_id']){
                    $file = MerchantFileService::info($val['image_id']);
                    if($file && isset($file['file_url'])){
                        $shop_product_goods[$key]['image_url'] =$file['file_url'];
                    }
                }
                if($val['activity_image_id']){
                    $file = MerchantFileService::info($val['activity_image_id']);
                    if($file && isset($file['file_url'])){
                        $shop_product_goods[$key]['activity_image_url'] =$file['file_url'];
                    }
                }
                if($val['content']){
                    $content_files = Db::name('merchant_file')
                        ->where('is_disable',0)
                        ->where('is_delete',0)
                        ->where('file_id','in',explode(',',$val['content']))
                        ->when($merchantId>0, function($query) use ($merchantId) {
                            $query->where('mer_id', $merchantId);
                        })
                        ->select()
                        ->toArray();
                    foreach ($content_files as $c_k=>$c_v){
                        $content_files[$c_k]['file_url'] = SettingService::fileUrl($c_v);
                    }
                    $shop_product_goods[$key]['content'] =$content_files;
                }else{
                    $shop_product_goods[$key]['content'] =[];
                }
            }
            $info['product_goods'] =$shop_product_goods;
            /***************************************进店方式***********************************************************/
            $info['release_order_num'] =0;//放单总数
            $shop_product_enter =Db::name('shop_product_enter')->where(['shop_product_id' => $info['id']])->select()->toArray();

            foreach ($shop_product_enter as $key=>$val){
                $info['release_order_num'] +=$val['order_num'];
                if($val['qr_image_id']){
                    $file = MerchantFileService::info($val['qr_image_id']);
                    if($file && isset($file['file_url'])){
                        $shop_product_enter[$key]['qr_image_url'] =$file['file_url'];
                    }
                }
                if($val['comment_vido_id']){
                    $file = MerchantFileService::info($val['comment_vido_id']);
                    if($file && isset($file['file_url'])){
                        $shop_product_enter[$key]['comment_vido_url'] =$file['file_url'];
                    }
                }
                if($val['comment_image_id']){
                    $files = Db::name('merchant_file')
                        ->where('is_disable',0)
                        ->where('is_delete',0)
                        ->where('file_id','in',explode(',',$val['comment_image_id']))
                        ->when($merchantId>0, function($query) use ($merchantId) {
                            $query->where('mer_id', $merchantId);
                        })
                        ->select()
                        ->toArray();
                    foreach ($files as $k=>$v){
                        $files[$k]['file_url'] = SettingService::fileUrl($v);
                    }
                    $shop_product_enter[$key]['comment_image_id'] =$files;
                }else{
                    $shop_product_enter[$key]['comment_image_id'] =[];
                }


            }
            $info['enter_shop_types'] =$shop_product_enter;
            /***************************************放单计划***********************************************************/
            $info['creat_order_plan'] =Db::name('shop_product_release')->where(['shop_product_id' => $info['id']])->select()->toArray();
            $info['d_comment_type'] =[];//评论
            //时间范围
            if($info['e_time_type'] ==1){
                $start_time =Db::name('shop_product_release')->where(['shop_product_id' => $info['id']])->value('MIN(start_time) AS start_time');
                $ent_time =Db::name('shop_product_release')->where(['shop_product_id' => $info['id']])->value('MAX(ent_time) AS ent_time');
                if($start_time && $ent_time){
                    $info['e_order_time'] = [$start_time,$ent_time];
                }
            }

            /***************************************增值***********************************************************/
            //查询增值佣金
            $increment_where[] = ['is_disable','<>',1];
            $increment_where[] = ['status','=',1];
            $increment_res = Db::name('setting_price_range')->where($increment_where)->field('id')->select()->toArray();
            $f_increment_values =[];
            foreach ($increment_res as $k=>$v){
                $range_id_0 = 'price_range_'.$v['id'].'_0';
                $range_id_1 = 'price_range_'.$v['id'].'_1';
                $range_id_2 = 'price_range_'.$v['id'].'_2';
                $range_id_3 = 'price_range_'.$v['id'].'_3';
                $range_id_4 = 'price_range_'.$v['id'].'_4';
                $f_increment_values['price_range_'.$v['id']] = null;//订单数量
                $f_increment_values[$range_id_0] = null;//单选框选择值
                $f_increment_values[$range_id_1] = [];
                $f_increment_values[$range_id_2] = null;
                $f_increment_values[$range_id_3] = [];
                $f_increment_values[$range_id_4] = [];
            }

            $shop_product_increment = Db::name('shop_product_increment')->where(['shop_product_id' => $info['id']])->select()->toArray();
            $info['f_increment_ids'] = [];
            foreach ($shop_product_increment as $key=>$val){
                $info['f_increment_ids'][] = $val['setting_price_range_id'];//增值id
                $f_increment_values['price_range_'.$val['setting_price_range_id']] = $val['order_num'];//订单数量
                $range_id_0 = 'price_range_'.$val['setting_price_range_id'].'_0';
                $range_id_1 = 'price_range_'.$val['setting_price_range_id'].'_1';
                $range_id_2 = 'price_range_'.$val['setting_price_range_id'].'_2';
                $range_id_3 = 'price_range_'.$val['setting_price_range_id'].'_3';
                $range_id_4 = 'price_range_'.$val['setting_price_range_id'].'_4';
                $f_increment_values[$range_id_0] = null;//单选框选择值
                $f_increment_values[$range_id_1] = [];
                $f_increment_values[$range_id_2] = null;
                $f_increment_values[$range_id_3] = [];
                $f_increment_values[$range_id_4] = [];
                if($val['condition_value']){
                    $condition_value = json_decode($val['condition_value'],true);
                    if(isset($condition_value[$range_id_0])){
                        $f_increment_values[$range_id_0] = $condition_value[$range_id_0];
                    }
                    if(isset($condition_value[$range_id_1])){
                        $f_increment_values[$range_id_1] = $condition_value[$range_id_1];
                    }
                    if(isset($condition_value[$range_id_2])){
                        $f_increment_values[$range_id_2] = $condition_value[$range_id_2];
                    }
                    if(isset($condition_value[$range_id_3])){
                        $f_increment_values[$range_id_3] = $condition_value[$range_id_3];
                    }
                    if(isset($condition_value[$range_id_4])){
                        $f_increment_values[$range_id_4] = $condition_value[$range_id_4];
                    }
                }
            }
            $info['f_increment_values'] =$f_increment_values;//增值选中值
            /***************************************备注图片***********************************************************/
            if($info['remark_images']){
                $remark_files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$info['remark_images']))
                    ->when($merchantId>0, function($query) use ($merchantId) {
                        $query->where('mer_id', $merchantId);
                    })
                    ->select()
                    ->toArray();
                foreach ($remark_files as $k=>$v){
                    $remark_files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $info['remark_images'] =$remark_files;
            }else{
                $info['remark_images'] =[];
            }
            /***************************************价格明细***********************************************************/
            $info['price_details'] =Db::name('shop_product_price')
                ->where(['shop_product_id' => $info['id']])
                ->field('data_id as id,code,type,title,price_describe,price,order_num,subtotal')
                ->select()
                ->toArray();//价格明细
            ShopProductCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 商品管理添加
     *
     * @param array $param 商品管理信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new ShopProductModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        // 启动事务
        $model->startTrans();
        try {
            $param['merchant_id']  = mer_id(true);
            $param['create_uid']  = mer_user_id();
            $param['create_time'] = datetime();
            //备注图片
            $remark_images =[];
            foreach ($param['remark_images'] as $k=>$v){
                array_push($remark_images,$v['file_id']);
            }
            $param['remark_images']= implode(',',$remark_images);
            //主表保存
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            // 添加商品信息
            if (isset($param['product_goods'])) {
                $setting_store_type_id = null;//商品分类ID
                $goods_insert = array();
                $b_product_num = 0;//商品数量
                $b_product_price = 0;//商品下单金额
                foreach ($param['product_goods'] as $k=>$goods_v) {
                    if($k==0){
                        $setting_store_type_id =$goods_v['setting_store_type_id'];
                    }
                    $content_ids = [];//商品详情
                    if(isset($goods_v['content'])){
                        foreach ($goods_v['content'] as $c_k=>$c_v){
                            array_push($content_ids,$c_v['file_id']);
                        }
                    }
                    array_push($goods_insert,[
                        'shop_product_id'=>$id,//商品主表ID
                        'setting_store_type_id'=>$setting_store_type_id,//商品分类ID
                        'goods_url'=>isset($goods_v['goods_url'])?$goods_v['goods_url']:null,//商品链接
                        'third_id'=>isset($goods_v['third_id'])?$goods_v['third_id']:null,//第三方平台商品ID
                        'goods_title'=>isset($goods_v['goods_title'])?$goods_v['goods_title']:null,//商品名称
                        'image_id'=>isset($goods_v['image_id'])?$goods_v['image_id']:null,//商品主图ID
                        'goods_spec'=>isset($goods_v['goods_spec'])?$goods_v['goods_spec']:null,//商品规格
                        'show_price'=>isset($goods_v['show_price'])?$goods_v['show_price']:0,//展示价格
                        'order_price'=>isset($goods_v['order_price'])?$goods_v['order_price']:0,//下单价格
                        'goods_num'=>isset($goods_v['goods_num'])?$goods_v['goods_num']:0,//每单拍(件)
                        'activity_title'=>isset($goods_v['activity_title'])?$goods_v['activity_title']:null,//活动标题
                        'activity_image_id'=>isset($goods_v['activity_image_id'])?$goods_v['activity_image_id']:null,//活动主图
                        'activity_price'=>isset($goods_v['activity_price'])?$goods_v['activity_price']:0,//活动价格
                        'shop_product_type_code'=>$param['shop_product_type_code'],//活动类型编码
                        'is_delivery'=>isset($goods_v['is_delivery'])?$goods_v['is_delivery']:1,//是否包邮:0、否 1、是
                        'content'=>implode(',',$content_ids),
                    ]);
                    switch ($param['shop_product_type_code']){
                        case 'PTBT':
                            //下单价格
                            $b_product_price =bcadd(
                                $b_product_price,
                                bcsub($goods_v['order_price'], $goods_v['activity_price'],2),
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                        case 'DFRW':
                            //下单价格*下单件数
                            $b_product_price =bcadd(
                                $b_product_price,
                                bcmul($goods_v['order_price'], $goods_v['goods_num'],2),
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                $goods_v['goods_num'],
                                0
                            );
                            break;
                        case 'LLRW':
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                        default:
                            //下单价格
                            $b_product_price =bcadd(
                                $b_product_price,
                                $goods_v['order_price'],
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                    }
                }
                $model->b_product_price = $b_product_price;
                $model->b_product_num = $b_product_num;
                $goods_add = ShopProductGoodsModel::insertAll($goods_insert);
            }

            // 添加进店方式
            $order_num = 0;
            if (isset($param['enter_shop_types'])) {
                //处理好评图片
                $comment_insert = array();
                foreach ($param['enter_shop_types'] as $key=>$enter_val){
                    $comment_image_ids =[];
                    if(isset($enter_val['comment_image_id']) && count($enter_val['comment_image_id'])>0){
                        foreach ($enter_val['comment_image_id'] as $k=>$v){
                            array_push($comment_image_ids,$v['file_id']);
                        }
                    }
                    array_push($comment_insert,[
                        'shop_product_id'=>$id,//商品主表ID
                        'comment_type'=>isset($enter_val['comment_type'])?$enter_val['comment_type']:null,//评论类型
                        'enter_type'=>isset($enter_val['enter_type'])?$enter_val['enter_type']:null,//进店方式：关键词、口令、二维码、链接
                        'merchant_fees'=>isset($enter_val['merchant_fees'])?$enter_val['merchant_fees']:0,//商家收费
                        'user_consumption'=>isset($enter_val['user_consumption'])?$enter_val['user_consumption']:0,//用户补贴
                        'setting_price_range_id'=>isset($enter_val['setting_price_range_id'])?$enter_val['setting_price_range_id']:null,//价格区间表ID
                        'spec'=>isset($enter_val['spec'])?$enter_val['spec']:null,//规格
                        'order_num'=>isset($enter_val['order_num'])?$enter_val['order_num']:0,//订单数
                        'keyword'=>isset($enter_val['keyword'])?$enter_val['keyword']:null,//关键词、口令、链接
                        'qr_image_id'=>isset($enter_val['qr_image_id'])?$enter_val['qr_image_id']:null,//二维码
                        'content'=>isset($enter_val['content'])?$enter_val['content']:null,//好评内容
                        'comment_image_id'=>implode(',',$comment_image_ids),//好评图片(多张逗号隔开)
                        'comment_vido_id'=>isset($enter_val['comment_vido_id'])?$enter_val['comment_vido_id']:null,//好评视频
                    ]);
                    $order_num +=$enter_val['order_num'];
                }
                $enter_add = ShopProductEnterModel::insertAll($comment_insert);
            }
            if($order_num!=$param['order_num']){
                $param['order_num'] = $order_num;
                exception("订单总数有误");
            }
            //放单计划处理
            $release_list = self::orderRelease($param,$id);
            if($release_list){
                $release_add = ShopProductReleaseModel::insertAll($release_list);
            }
            //增值服务
            $increment_list = self::incrementMachining($param,$id);
            if($increment_list){
                $increment_add = ShopProductIncrementModel::insertAll($increment_list);
            }
            //费用明细
            $price_details = self::priceDetail($param,$id);
            if($price_details){
                //判断是否与前端计算过来总价相匹配
                $h_subtotal = array_sum(array_column($price_details,'subtotal'));
                $q_subtotal = array_sum(array_column($param['price_details'],'subtotal'));
                if($h_subtotal !=$q_subtotal){
                    exception($h_subtotal."价格计算有误，请稍后再试".$q_subtotal);
                }
                //获取本金
                $principal = 0;
                foreach ($price_details as $key=>$val){
                    if($val['type'] == 'refund_principal'){
                        $principal = bcadd($principal,$val['subtotal'],2);
                    }
                }
                $model->status = ShopProductModel::getStatus('wait_pay',1);//待支付
                $model->money = $h_subtotal;//总金额
                $model->principal = $principal;//本金
                $model->commission = bcsub($h_subtotal,$principal,2);//佣金
                //保存费用明细
                $price_add = ShopProductPriceModel::insertAll($price_details);
            }
            $model->save();
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param[$pk] = $model->$pk;
        //支付
        self::pay([$model->$pk]);
        return $param;
    }

    /**
     * 商品支付
     * @Author: 易军辉
     * @DateTime:2024-06-20 19:27
     * @param $ids 商品IDS
     */
    public static function pay($ids)
    {
        Db::startTrans();
        try {
            $list = Db::name('shop_product')
                ->where('id', 'in', $ids)
                ->where('is_disable', 0)
                ->where('is_delete', 0)
                ->where('status', ShopProductModel::getStatus('wait_pay', 1))
                ->field('id,money,principal,commission,merchant_shop_id,merchant_id,setting_refund_id')
                ->select()
                ->toArray();
            if(count($list)<=0){
                exception('未找到需要支付的商品');
            }
            $refund_id = SettingRefundModel::getRefundType(SettingRefundModel::SJFK,1);
            foreach ($list as $key => $val) {
                $money = $val['money'];
                $principal = $val['principal'];
                $commission = $val['commission'];
                //商家返款
                if($val['setting_refund_id'] == $refund_id){
                    $principal = 0;
                    $money = $commission;
                }
                $consumption_res = MerchantService::consumption($money,$principal,$commission, '发布商品', $val['id'], $val['merchant_shop_id'],'商品编号：'.$val['id'],$val['merchant_id']);
                if ($consumption_res) {
                    $edit = Db::name('shop_product')
                        ->where('id', $val['id'])
                        ->update([
                            'status' => ShopProductModel::getStatus('wait_auth', 1),
                            'h_pay_time' => datetime(),
                            'h_pay_type' => 1
                        ]);
                    if (empty($edit)) {
                        exception('支付失败');
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 费用明细计算
     * @Author: 易军辉
     * @DateTime:2024-06-06 14:36
     * @param $param
     */
    private static function priceDetail($param,$id){
        $insert = array();
        /**************************店铺平台服务费(商家收费*总订单数)***********************************/
        $store_platform = Db::name('setting_store_platform')->where('id',$param['store_platform_id'])->field('id,title,code,service_money')->find();
        if($store_platform['service_money']>0){
            self::addPrice(
                $insert,
                $id,
                $store_platform['id'],
                $store_platform['code'],
                'platform',
                '平台服务费',
                $store_platform['service_money'].'元/单',
                $store_platform['service_money'],
                $param['order_num'],
                0,
                $store_platform['service_money'],
            );
        }
        /**************************返款本金***********************************/
        $refund_price = 0;//返款金额
        $basic_price = 0;//基础佣金金额
        foreach ($param['product_goods'] as $k=>$v){
            switch ($param['shop_product_type_code']){
                case 'PTBT':
                    //下单价格-活动价格
                    $refund_price =bcadd(
                            $refund_price,
                            bcsub($v['order_price'], $v['activity_price'],2),
                            2
                        );
                    //下单价格
                    $basic_price =bcadd(
                        $basic_price,
                        $v['order_price'],
                        2
                    );
                    break;
                case 'DFRW':
                    //下单价格*下单件数
                    $refund_price =bcadd(
                        $refund_price,
                        bcmul($v['order_price'], $v['goods_num'],2),
                        2
                    );
                    $basic_price =bcadd(
                        $basic_price,
                        bcmul($v['order_price'], $v['goods_num'],2),
                        2
                    );
                    break;
                case 'LLRW':
                    $refund_price = 0;
                    //显示价格
                    $basic_price =bcadd(
                        $basic_price,
                        $v['show_price'],
                        2
                    );
                    break;
                default:
                    $refund_price =bcadd(
                        $refund_price,
                        $v['order_price'],
                        2
                    );
                    $basic_price =bcadd(
                        $basic_price,
                        $v['order_price'],
                        2
                    );
                    break;
            }
        }
        if($refund_price>0 || $param['shop_product_type_code']== 'LLRW'){
            self::addPrice(
                $insert,
                $id,
                null,
                'refund_principal',
                'refund_principal',
                ($param['shop_product_type_code']== 'PTBT'?'活动补贴':'返款本金'),
                $refund_price.'元/单',
                $refund_price,
                $param['order_num'],
                $refund_price,
                0,
            );
        }
        /**************************平台返款/商家返款***********************************/
        $setting_refund = Db::name('setting_refund')->where('id',$param['setting_refund_id'])->field('id,title,code,price')->find();
        if($setting_refund){
            self::addPrice(
                $insert,
                $id,
                $setting_refund['id'],
                $setting_refund['code'],
                'refund',
                $setting_refund['title'],
                $setting_refund['price'].'元/单',
                $setting_refund['price'],
                $param['order_num'],
                0,
                $setting_refund['price'],
            );
        }
        /**************************基础佣金***********************************/
        $sub = SettingPriceAttributesModel::subQuery($param['store_platform_id'],$param['shop_product_type_id']);
        $price_range = Db::name('setting_price_range')
            ->alias('s')
            ->join([$sub => 'a'],'s.id = a.setting_price_range_id')
            ->where('s.price_start','<',$basic_price)
            ->where('s.price_close','>=',$basic_price)
            ->where('s.status',0)
            ->where('s.is_delete',0)
            ->where('s.is_disable',0)
            ->field('s.id,s.code,s.merchant_fees,s.user_consumption,s.price_start,s.price_close')
            ->order('s.price_close,s.id','desc')
            ->find();
        if(!$price_range){
            exception("请联系平台配置基础佣金");
        }else{
            self::addPrice(
                $insert,
                $id,
                $price_range['id'],
                $price_range['code'],
                'basic_price',
                '基础佣金',
                $price_range['merchant_fees'].'元/单',
                $price_range['merchant_fees'],
                $param['order_num'],
                $price_range['user_consumption'],
                $price_range['merchant_fees'],
            );
        }
        /**************************评价***********************************/
        $range_ids = array_column($param['enter_shop_types'],'setting_price_range_id');
        if($range_ids){
            $comment_list = Db::name('setting_price_range')
                ->where('id','in',$range_ids)
                ->where('status',2)
                ->where('is_delete',0)
                ->where('is_disable',0)
                ->field('id,code,merchant_fees,user_consumption,comment_type')
                ->order('price_close,id','desc')
                ->select();
            foreach ($comment_list as $k=>$v){
                if($v['merchant_fees']>0){
                    $c_order_num = 0;//评论数量
                    foreach ($param['enter_shop_types'] as $k1=>$v1){
                        if($v['comment_type'] == $v1['comment_type']){
                            $c_order_num += $v1['order_num'];
                        }
                    }
                    self::addPrice(
                        $insert,
                        $id,
                        $v['id'],
                        $v['code'],
                        'comment_price',
                        SettingPriceRangeModel::getCommentType($v['comment_type'],1),
                        $v['merchant_fees'].'元/单',
                        $v['merchant_fees'],
                        $c_order_num,
                        $v['user_consumption'],
                        $v['merchant_fees'],
                    );
                }
            }
        }
        /**************************增值服务***********************************/
        if($param['f_increment_ids']) {
            $increment_list = Db::name('setting_price_range')
                ->where('id', 'in', $param['f_increment_ids'])
                ->where('status', 1)
                ->where('is_delete', 0)
                ->where('is_disable', 0)
                ->where('merchant_fees', '>',0)//不收费的过滤掉
                ->field('id,code,merchant_fees,user_consumption,mer_describe')
                ->order('price_close,id', 'desc')
                ->select();
            foreach ($increment_list as $k=>$v) {
                //获取订单数
                $order_num = $param['f_increment_values']['price_range_' . $v['id']];
                if (!$order_num || $order_num>$param['order_num']) {
                    $order_num = $param['order_num'];
                }
                $merchant_fees = $v['merchant_fees'];
                //附加宝贝金额计算
                if($v['code']=='Additional_products'){
                    $merchant_fees = bcmul($merchant_fees,(count($param['product_goods'])-1),2);
                    $order_num = $param['order_num'];
                }
                self::addPrice(
                    $insert,
                    $id,
                    $v['id'],
                    $v['code'],
                    'increment',
                    $v['mer_describe'],
                    $merchant_fees.'元/单',
                    $merchant_fees,
                    $order_num,
                    $v['user_consumption'],
                    $v['merchant_fees'],
                );
            }
        }
        return $insert;
    }


    /**
     * 组装价格明细
     * @Author: 易军辉
     * @DateTime:2024-06-06 15:45
     * @param $insert
     * @param $id 主表ID
     * @param $data_id 关联数据ID
     * @param $code 编码
     * @param $type 类型
     * @param $title 费用名称
     * @param $price_describe 单价说明
     * @param $price 单价
     * @param $order_num 订单数量
     * @param $user_price 买手所得单价
     * @param $platform_price 平台所得单价
     */
    private static function addPrice(&$insert=[],$id=null,$data_id=null, $code=null, $type=null, $title=null, $price_describe=null, $price=0, $order_num=0, $user_price=0, $platform_price=0)
    {
        array_push($insert,[
            'data_id'=>$data_id,
            'shop_product_id'=>$id,
            'code'=>$code,
            'type'=>$type,
            'title'=>$title,
            'price_describe'=>$price_describe,
            'price'=>$price,
            'order_num'=>$order_num,
            'subtotal'=>bcmul($price,$order_num,2),
            'user_price'=>$user_price,
            'user_fee'=>bcmul($user_price,$order_num,2),
            'platform_price'=>$platform_price,
            'platform_fee'=>bcmul($platform_price,$order_num,2),
        ]);
    }
    /**
     * 增值服务处理
     * @Author: 易军辉
     * @DateTime:2024-06-05 20:53
     * @param $param
     */
    private static function incrementMachining($param,$id)
    {
        $increment = array();
        if(count($param['f_increment_ids'])>0){
            $increment_where[] = ['is_disable','<>',1];
            $increment_where[] = ['status','=',1];
            $increment_where[] = ['id','in',$param['f_increment_ids']];
            $list = SettingPriceRangeService::list(where_delete($increment_where),0,0);
            foreach ($list as $k=>$v){
                //获取订单数
                $order_num = $param['f_increment_values']['price_range_'.$v['id']];
                if(!$order_num){
                    $order_num = $param['order_num'];
                }
                //获取条件值
                $condition_value = [];
                $condition_type =[];
                for($i=0;$i<5;$i++){
                    $c_val = $param['f_increment_values']['price_range_'.$v['id'].'_'.$i];
                    if($c_val!=null && $c_val!=[]){
                        $condition_value['price_range_'.$v['id'].'_'.$i] = $c_val;
                        array_push($condition_type,$i);
                    }
                }
                array_push($increment,[
                    'shop_product_id'=>$id,
                    'setting_price_range_id'=>$v['id'],//价格区间表ID
                    'setting_price_condition_type'=>$condition_type?implode(",",$condition_type):null,//价格区间条件类型
                    'setting_price_range_code'=>$v['code'],//增值项编码
                    'mer_describe'=>$v['mer_describe'],//增值项名称
                    'merchant_fees'=>$v['merchant_fees'],//商家收费
                    'user_consumption'=>$v['user_consumption'],//用户消耗
                    'order_num'=>$order_num,//订单数量
                    'condition_value'=>$condition_value?json_encode($condition_value):null,//条件值(json组装)
                ]);
            }
        }
        return $increment;
    }

    /**
     * 设置放单计划处理
     * @Author: 易军辉
     * @DateTime:2024-06-05 17:43
     */
    private  static function orderRelease($param,$id)
    {
        $data = array();
        switch (intval($param['e_time_type'])){
            case 0:
                //间隔模式
                if (isset($param['creat_order_plan'])) {
                    foreach ($param['creat_order_plan'] as $k=>$v){
                        $v['type'] = $param['e_time_type'];

                        if($v['order_num']>$v['total_order_num']){
                            $v['order_num'] = $v['total_order_num'];
                        }
                        //获取下放次数
                        $frequency = ceil(bcdiv($v['total_order_num'],$v['order_num'],2));
                        $minute = $frequency * $v['interval_minutes'];
                        // 将开始时间转换为 DateTime 对象
                        $start_time = new DateTime($v['start_time']);
                        // 添加分钟数到开始时间
                        $start_time->modify("+$minute minutes");
                        $v['ent_time'] = $start_time->format('Y-m-d H:i:s');
                        $v['shop_product_id']=$id;
                        if(isset($v['id'])){
                            unset($v['id']);
                        }
                        array_push($data,[
                            'shop_product_id'=>$id,
                            'start_time'=>$v['start_time'],//开始时间
                            'ent_time'=>$v['ent_time'],//结束时间
                            'interval_minutes'=>$v['interval_minutes'],//间隔分钟
                            'order_num'=>$v['order_num'],//放出几单
                            'total_order_num'=>$v['total_order_num'],//共放出几单
                            'release_num'=>0,//已放出几单
                            'type'=>$v['type'],//放单类型：0、间隔模式 1、立刻放单
                        ]);
                    }
                }
                break;
            case 1:
                //立刻放单
                if(isset($param['e_order_time']) && count($param['e_order_time'])==2){
                    //时间范围内有多少分钟
                    $minute = minuteCalculation($param['e_order_time'][0],$param['e_order_time'][1]);
                    //分钟除以总订单数计算出间隔分钟
                    $interval_minutes =bcdiv($minute,$param['order_num'],0);
                    if (intval($interval_minutes) == $interval_minutes && $interval_minutes > 0) {
                        $order_num = 1;
                        $interval_minutes =intval($interval_minutes);
                    }else{
                        $interval_minutes = 0;
                        $order_num = $param['order_num'];
                    }
                    array_push($data,[
                        'shop_product_id'=>$id,
                        'start_time'=>$param['e_order_time'][0],//开始时间
                        'ent_time'=>$param['e_order_time'][1],//结束时间
                        'interval_minutes'=>$interval_minutes,//间隔分钟
                        'order_num'=>$order_num,//放出几单
                        'total_order_num'=>$param['order_num'],//共放出几单
                        'release_num'=>0,//已放出几单
                        'type'=>$param['e_time_type'],//放单类型：0、间隔模式 1、立刻放单
                    ]);
                }
                break;
        }
        return $data;
    }

     /**
     * 商品管理修改
     *
     * @param int|array $ids   商品管理id
     * @param array     $param 商品管理信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new ShopProductModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids'], $param['merchant_id'],$param['status'],$param['money'],$param['h_pay_time'],$param['h_pay_type']);
        $model = $model->where('id',$ids)->find();
        if (empty($model)) {
            exception();
        }
        if($model->status!=ShopProductModel::getStatus('wait_pay',1) && $model->status!=ShopProductModel::getStatus('auth_error',1)){
            exception("当前状态不支持修改");
        }
        // 启动事务
        $model->startTrans();
        try {
            $param['update_uid']  = mer_user_id();
            $param['update_time'] = datetime();
            //备注图片
            $remark_images =[];
            foreach ($param['remark_images'] as $k=>$v){
                array_push($remark_images,$v['file_id']);
            }
            $param['remark_images']= implode(',',$remark_images);
            //主表保存
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            // 添加商品信息
            if (isset($param['product_goods'])) {
                $goods_del = ShopProductGoodsModel::where('shop_product_id',$id)->delete();
                $setting_store_type_id = null;//商品分类ID
                $goods_insert = array();
                $b_product_num = 0;//商品数量
                $b_product_price = 0;//商品下单金额
                foreach ($param['product_goods'] as $k=>$goods_v) {
                    if($k==0){
                        $setting_store_type_id =$goods_v['setting_store_type_id'];
                    }
                    array_push($goods_insert,[
                        'shop_product_id'=>$id,//商品主表ID
                        'setting_store_type_id'=>$setting_store_type_id,//商品分类ID
                        'goods_url'=>isset($goods_v['goods_url'])?$goods_v['goods_url']:null,//商品链接
                        'goods_title'=>isset($goods_v['goods_title'])?$goods_v['goods_title']:null,//商品名称
                        'image_id'=>isset($goods_v['image_id'])?$goods_v['image_id']:null,//商品主图ID
                        'goods_spec'=>isset($goods_v['goods_spec'])?$goods_v['goods_spec']:null,//商品规格
                        'show_price'=>isset($goods_v['show_price'])?$goods_v['show_price']:0,//展示价格
                        'order_price'=>isset($goods_v['order_price'])?$goods_v['order_price']:0,//下单价格
                        'goods_num'=>isset($goods_v['goods_num'])?$goods_v['goods_num']:0,//每单拍(件)
                        'activity_title'=>isset($goods_v['activity_title'])?$goods_v['activity_title']:null,//活动标题
                        'activity_image_id'=>isset($goods_v['activity_image_id'])?$goods_v['activity_image_id']:null,//活动主图
                        'activity_price'=>isset($goods_v['activity_price'])?$goods_v['activity_price']:0,//活动价格
                        'shop_product_type_code'=>$param['shop_product_type_code'],//活动类型编码
                        'is_delivery'=>isset($goods_v['is_delivery'])?$goods_v['is_delivery']:1,//是否包邮:0、否 1、是
                    ]);
                    switch ($param['shop_product_type_code']){
                        case 'PTBT':
                            //下单价格
                            $b_product_price =bcadd(
                                $b_product_price,
                                $goods_v['order_price'],
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                        case 'DFRW':
                            //下单价格*下单件数
                            $b_product_price =bcadd(
                                $b_product_price,
                                bcmul($goods_v['order_price'], $goods_v['goods_num'],2),
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                $goods_v['goods_num'],
                                0
                            );
                            break;
                        case 'LLRW':
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                        default:
                            //下单价格
                            $b_product_price =bcadd(
                                $b_product_price,
                                $goods_v['order_price'],
                                2
                            );
                            //下单数量
                            $b_product_num =bcadd(
                                $b_product_num,
                                1,
                                0
                            );
                            break;
                    }
                }
                $model->b_product_price = $b_product_price;
                $model->b_product_num = $b_product_num;
                $goods_add = ShopProductGoodsModel::insertAll($goods_insert);
            }

            // 添加进店方式
            $order_num = 0;
            if (isset($param['enter_shop_types'])) {
                $enter_del = ShopProductEnterModel::where('shop_product_id',$id)->delete();
                //处理好评图片
                $comment_insert = array();
                foreach ($param['enter_shop_types'] as $key=>$enter_val){
                    $comment_image_ids =[];
                    if(isset($enter_val['comment_image_id']) && count($enter_val['comment_image_id'])>0){
                        foreach ($enter_val['comment_image_id'] as $k=>$v){
                            array_push($comment_image_ids,$v['file_id']);
                        }
                    }
                    array_push($comment_insert,[
                        'shop_product_id'=>$id,//商品主表ID
                        'comment_type'=>isset($enter_val['comment_type'])?$enter_val['comment_type']:null,//评论类型
                        'enter_type'=>isset($enter_val['enter_type'])?$enter_val['enter_type']:null,//进店方式：关键词、口令、二维码、链接
                        'merchant_fees'=>isset($enter_val['merchant_fees'])?$enter_val['merchant_fees']:0,//商家收费
                        'user_consumption'=>isset($enter_val['user_consumption'])?$enter_val['user_consumption']:0,//用户补贴
                        'setting_price_range_id'=>isset($enter_val['setting_price_range_id'])?$enter_val['setting_price_range_id']:null,//价格区间表ID
                        'spec'=>isset($enter_val['spec'])?$enter_val['spec']:null,//规格
                        'order_num'=>isset($enter_val['order_num'])?$enter_val['order_num']:0,//订单数
                        'keyword'=>isset($enter_val['keyword'])?$enter_val['keyword']:null,//关键词、口令、链接
                        'qr_image_id'=>isset($enter_val['qr_image_id'])?$enter_val['qr_image_id']:null,//二维码
                        'content'=>isset($enter_val['content'])?$enter_val['content']:null,//好评内容
                        'comment_image_id'=>implode(',',$comment_image_ids),//好评图片(多张逗号隔开)
                        'comment_vido_id'=>isset($enter_val['comment_vido_id'])?$enter_val['comment_vido_id']:null,//好评视频
                    ]);
                    $order_num +=$enter_val['order_num'];
                }
                $enter_add = ShopProductEnterModel::insertAll($comment_insert);
            }
            if($order_num!=$param['order_num']){
                $param['order_num'] = $order_num;
                exception("订单总数有误");
            }
            //放单计划处理
            $release_list = self::orderRelease($param,$id);
            if($release_list){
                $release_del = ShopProductReleaseModel::where('shop_product_id',$id)->delete();
                $release_add = ShopProductReleaseModel::insertAll($release_list);
            }

            //增值服务
            $increment_list = self::incrementMachining($param,$id);
            if($increment_list){
                $increment_del = ShopProductIncrementModel::where('shop_product_id',$id)->delete();
                $increment_add = ShopProductIncrementModel::insertAll($increment_list);
            }
            //费用明细
            $price_details = self::priceDetail($param,$id);
            if($price_details){
                //判断是否与前端计算过来总价相匹配
                $h_subtotal = array_sum(array_column($price_details,'subtotal'));
                $q_subtotal = array_sum(array_column($param['price_details'],'subtotal'));
                if($h_subtotal !=$q_subtotal){
                    exception($h_subtotal."价格计算有误，请稍后再试".$q_subtotal);
                }
                //获取本金
                $principal = 0;
                foreach ($price_details as $key=>$val){
                    if($val['type'] == 'refund_principal'){
                        $principal = bcadd($principal,$val['subtotal'],2);
                    }
                }
                //佣金
                $commission = bcsub($h_subtotal,$principal,2);
                /********************************金额多退少补*********************************************/
                if($model->status != ShopProductModel::getStatus('wait_pay',1) && $model->money!=$h_subtotal){
                    if($h_subtotal>$model->money){
                        $consumption_res = MerchantService::consumption(
                            bcsub($h_subtotal,$model->money,2),
                            bcsub($principal,$model->principal,2),
                            bcsub($commission,$model->commission,2),
                            '修改商品补差价',
                            $id,
                            $param['merchant_shop_id'],
                            "商品编号：".$id
                        );
                    }else{
                        $consumption_res = MerchantService::refund(
                            $model->merchant_id,
                            bcsub($model->money,$h_subtotal,2),
                            bcsub($model->principal,$principal,2),
                            bcsub($model->commission,$commission,2),
                            '修改商品退差价',
                            $id,
                            $param['merchant_shop_id'],
                            "商品编号：".$id
                        );
                    }
                }else if($model->status == ShopProductModel::getStatus('wait_pay',1)){
                    $consumption_res = MerchantService::consumption(
                        $h_subtotal,
                        $principal,
                        $commission,
                        '修改待支付商品付款',
                        $id,
                        $param['merchant_shop_id'],
                        "商品编号：".$id
                    );
                    if($consumption_res){
                        $model->status = ShopProductModel::getStatus('wait_auth',1);
                    }
                }
                //审核未通过状态更改为待审核
                if($model->status == ShopProductModel::getStatus('auth_error',1)){
                    $model->status = ShopProductModel::getStatus('wait_auth',1);
                }
                $price_del = ShopProductPriceModel::where('shop_product_id',$id)->delete();
                $price_add = ShopProductPriceModel::insertAll($price_details);
                $model->money = $h_subtotal;
                $model->principal = $principal;
                $model->commission = $commission;
                $model->h_pay_time = datetime();
                $model->h_pay_type = 1;
            }
            $model->save();
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        ShopProductCache::del($ids);
        return $param;
    }
    /**
     * 商品管理删除
     *
     * @param array $ids  商品管理id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new ShopProductModel();
        $pk = $model->getPk();
        $merchantId = mer_id();
        if ($real) {
            $res = $model
                ->where($pk, 'in', $ids)
                ->when($merchantId>0, function($query) use ($merchantId) {
                    $query->where('merchant_id', $merchantId);
                })
                ->where(function ($query){
                    $query->where('status',ShopProductModel::getStatus('wait_pay',1))//未支付
                    ->whereOr(function($query){
                        //状态为已撤销，并且撤销数量等于总订单数量
                        $query->where('status',ShopProductModel::getStatus('revoke',1))//已撤销
                        ->whereRaw("(
                                     SELECT COUNT(sub_o.id)
                                     FROM ya_shop_order AS sub_o
                                     WHERE sub_o.shop_product_id = ya_shop_product.id
                                       AND sub_o.status = '".ShopOrderModel::getStatus('o_revoke',1)."'
                                     ) = ya_shop_product.order_num");
                    });
                })
                ->delete();
        } else {
            $update = mer_delete_update();
            $res = $model
                ->where($pk, 'in', $ids)
                ->when($merchantId>0, function($query) use ($merchantId) {
                    $query->where('merchant_id', $merchantId);
                })
                ->where(function ($query){
                    $query->where('status',ShopProductModel::getStatus('wait_pay',1))//未支付
                    ->whereOr(function($query){
                        //状态为已撤销，并且撤销数量等于总订单数量
                        $query->where('status',ShopProductModel::getStatus('revoke',1))//已撤销
                        ->whereRaw("(
                                     SELECT COUNT(sub_o.id)
                                     FROM ya_shop_order AS sub_o
                                     WHERE sub_o.shop_product_id = ya_shop_product.id
                                       AND sub_o.status = '".ShopOrderModel::getStatus('o_revoke',1)."'
                                     ) = ya_shop_product.order_num");
                    });
                })
                ->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        ShopProductCache::del($ids);
        return $update;
    }

    /**
     * 商品审核
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function auth($ids, $param = [])
    {
        $model = new ShopProductModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('status',1)
            ->where($pk, 'in', $ids)
            ->field("id,auth_time,auth_uid,status,auth_msg,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,shop_product_type_code,order_num,b_product_num,b_product_price")
            ->select();
        if(count($list)<=0){
            exception("未有符合条件的商品需要审核");
        }
        self::$time_on = date('ymdHis');
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->auth_time=datetime();
                $v->auth_uid=user_id();
                switch (intval($param['auth_status'])){
                    case 0://待审核
                        $v->status=ShopProductModel::getStatus('wait_auth',1);
                        break;
                    case 1://审核通过
                        $v->status=ShopProductModel::getStatus('in',1);
                        $order_list = self::create_order($v);
                        if($order_list){
                           $add_order= Db::name('shop_order')->insertAll($order_list);
                        }
                        break;
                    case 2://审核未通过
                        $v->status=ShopProductModel::getStatus('auth_error',1);
                        $v->auth_msg=$param['auth_msg'];
                        break;
                }
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        ShopProductCache::del($ids);
        return $param;
    }

    /**
     * 创建订单
     * @param $product
     * @return void
     */
    private static function create_order($product){
        //进店方式
        $enters = Db::name('shop_product_enter')->where('shop_product_id',$product['id'])->select();
        $order_data = array();
        //订单号
//        $order_ons = self::generateOrderNumber($product['order_num']);
//        $order_on_index = 0;
        //查询费用明细
        $price_list = Db::name('shop_product_price')->where('shop_product_id',$product['id'])->select()->toArray();
        //查询放单计划
        $release_list = Db::name('shop_product_release')->where('shop_product_id',$product['id'])->select()->toArray();
        //查询不在费用明细内的增值服务
        $increment_list =  Db::query("SELECT * from ya_shop_product_increment where shop_product_id = ".$product['id']." and setting_price_range_id not in(
            SELECT data_id from ya_shop_product_price where shop_product_id = ".$product['id']." and type='increment'
        )");
        foreach ($enters as $key=>$val){
            //生成预计上架时间
            $grounding_time_res = self::generateGroundingTime($val,$release_list);
            $grounding_times = $grounding_time_res['grounding_times'];
            $release_list= $grounding_time_res['release_list'];
            for ($i=0;$i<$val['order_num'];$i++){
                $shop_product_price_ids = [];//费用明细ID
                $setting_price_range_ids = [];//增值服务ID
                $principal = 0;//本金
                $commission = 0;//买手所得佣金
                $mer_commission = 0;//商家支付的佣金
                $is_self_selection = 0;//是否自行买号
                foreach ($price_list as $k=>$v){
                    //好评方式佣金匹配
                    if($v['type'] == 'comment_price' && $v['order_num']>0){
                        if($v['data_id'] == $val['setting_price_range_id']){
                            $shop_product_price_ids[] = $v['id'];
                            $commission =bcadd(
                                $commission,
                                $v['user_price'],
                                2
                            );
                            //获取商家支付的佣金
                            $mer_commission =bcadd(
                                $mer_commission,
                                $v['price'],
                                2
                            );
                            $price_list[$k]['order_num'] = $v['order_num']-1;
                        }
                    }else if($v['order_num']>0){
                        //获取买手所得佣金
                        if(in_array($v['type'], ['basic_price','increment'])){
                            $shop_product_price_ids[] = $v['id'];
                            $commission =bcadd(
                                $commission,
                                $v['user_price'],
                                2
                            );
                            if($v['type'] == 'increment'){
                                $setting_price_range_ids[] = $v['data_id'];
                            }
                        }

                        //获取本金
                        if($v['type'] == 'refund_principal'){
                            $principal =bcadd(
                                $principal,
                                $v['price'],
                                2
                            );
                        }else{
                            //获取商家支付的佣金
                            $mer_commission =bcadd(
                                $mer_commission,
                                $v['price'],
                                2
                            );
                        }
                        //判断是否自选买号
                        if($v['type'] == 'increment' && $v['code'] == 'Self_selection'){
                            $is_self_selection = 1;
                        }
                        $price_list[$k]['order_num'] = $v['order_num']-1;
                    }
                }
                //免费增值服务id增加
                foreach ($increment_list as $increment_k=>$increment_v){
                    if($increment_v['order_num']>0){
                        $setting_price_range_ids[] = $increment_v['setting_price_range_id'];
                        $increment_list[$increment_k]['order_num'] = $increment_v['order_num']-1;
                    }
                }

                $order_data[] = [
                    'merchant_id'=>$product['merchant_id'],//商家ID
                    'merchant_shop_id'=>$product['merchant_shop_id'],//店铺ID
                    'store_platform_id'=>$product['store_platform_id'],//店铺平台ID
                    'setting_refund_id'=>$product['setting_refund_id'],//返款类型【平台补贴、商家返款】
                    'shop_product_type_id'=>$product['shop_product_type_id'],//活动类型【平台补贴、垫付任务、浏览任务】
                    'shop_product_type_code'=>$product['shop_product_type_code'],//活动类型【平台补贴、垫付任务、浏览任务】
                    'shop_product_id'=>$product['id'],//商品表ID
                    'shop_product_enter_id'=>$val['id'],//进店方式ID
                    'shop_product_price_ids'=>implode(',',$shop_product_price_ids),//费用明细ID(多个逗号隔开)
                    'setting_price_range_ids'=>implode(',',$setting_price_range_ids),//增值服务ID(多个逗号隔开)
                    'order_on'=>null,//订单号
                    'status'=>ShopOrderModel::getStatus('o_listing',1),//订单状态：10、撤销  0、待上架  1、待自选 2、待接单  3、待操作 4、待发货  5、待评价 6、评价待审核 7完成 8、审核未通过 9、暂停
                    'principal'=>$principal,//订单本金
                    'commission'=>$commission,//订单佣金
                    'mer_commission'=>$mer_commission,//订单佣金
                    'actual_amount'=>0,//实付金额
                    'add_comment_commission'=>0,//追评佣金
                    'is_self_selection'=>$is_self_selection,
                    'create_uid'=>user_id(),//添加用户id
                    'create_time'=>datetime(),//创建时间
                    'estimate_advertising_time'=>isset($grounding_times[$i])?$grounding_times[$i]:date('Y-m-d H:i:s'),//预计投放时间
                ];
//                $order_on_index++;

            }
        }
        return $order_data;
    }

    /**
     * 计算订单上架时间
     * @Author: 易军辉
     * @DateTime:2024-08-21 16:55
     * @param $enter
     * @param $release_list
     * @return array
     */
    private static function generateGroundingTime($enter,$release_list)
    {
        $grounding_times = [];
        foreach ($release_list as $key=>$val){
            for ($i=0;$i<$val['total_order_num'];$i++){
                if(count($grounding_times)<$enter['order_num'] && $release_list[$key]['total_order_num']>0){
                    //开始时间
                    $start_time = $val['start_time'];
                    // 将开始时间转换为 DateTime 对象
                    $start_time_model = new DateTime($start_time);
                    if($key>0){
                        // 添加分钟数到开始时间
                        $start_time_model->modify("+".$val['interval_minutes']." minutes");
                    }

                    $val['start_time'] =$start_time_model->format('Y-m-d H:i:s');
                    $release_list[$key]['start_time'] =$val['start_time'];
                    /************************一次需要放多少个时间****************************************/
                    $num = 0;
                    $cha_num = $enter['order_num'] -count($grounding_times);//还差多少个
                    if($cha_num<$val['order_num']){
                        $num = $cha_num;
                        //时间减去一次间隔时间
                        $time_model = new DateTime($val['start_time']);
                        $time_model->modify("-".$val['interval_minutes']." minutes");
                        $release_list[$key]['start_time'] =$time_model->format('Y-m-d H:i:s');
                    }else if($cha_num>$val['order_num']){
                        $num = $val['order_num'];
                    }else if($cha_num==$val['order_num']){
                        $num = $val['order_num'];
                    }
                    if($num>$release_list[$key]['total_order_num']){
                        $num =$release_list[$key]['total_order_num'];
                    }
                    for ($j=0;$j<$num;$j++){
                        array_push($grounding_times,$val['start_time']);
                    }
                    $release_list[$key]['total_order_num'] = $release_list[$key]['total_order_num']-$num;
                }else{
                    break;
                }
            }
            if(count($grounding_times)==$enter['order_num']){
                break;
            }
        }
        return compact('grounding_times','release_list');
    }
    /**
     * 批量生成订单号
     * @param $order_num 订单数量
     * @return void
     * @throws \think\db\exception\DbException
     */
    private static function generateOrderNumber($order_num)
    {
        $order_ons = array();
        $i =0;
        while (count($order_ons) < $order_num) {
            self::$time_on=bcadd(self::$time_on,1,0);
            $no = self::$time_on.str_pad($i + 1, 4, '0', STR_PAD_LEFT);
            if (!in_array($no, $order_ons)) {
                $order_ons[] = $no;
                $i++;
            }
        }
        //查询是否有重复
        $shop_orders = Db::name('shop_order')->where('order_on','in', $order_ons)->field('order_on')->select();
        foreach ($shop_orders as $key=>$val) {
            $index = array_search($val['order_on'], $order_ons);
            if ($index !== false) {
                $order_ons[$index] = $val['order_on'].$key;
            }
        }
        return $order_ons;
    }


    /**
     * 撤销
     * @Author: 易军辉
     * @DateTime:2024-06-20 18:06
     * @param $ids
     * @param $param $param['refund_type']退款方式：1、退商家本金 2、退商家佣金 3、扣买手本金 4、扣买手佣金
     */
    public static function revoke($ids, $param = [])
    {
        $merchantId = mer_id();
        $user_id = mer_user_id();
        if($user_id<=0){
            $user_id = user_id();
        }
        $list = Db::name('shop_product')
            ->where('id', 'in', $ids)
            ->where('is_disable', 0)
            ->where('is_delete', 0)
            ->where('h_pay_type', 1)
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId)
                    ->where('status','in',[
                        ShopProductModel::getStatus('in',1),
                        ShopProductModel::getStatus('auth_error',1)
                    ]);
            })
            ->field('id,money,principal,commission,merchant_shop_id,status,merchant_id,merchant_shop_id')
            ->select()
            ->toArray();
        Db::startTrans();
        try {
            foreach ($list as $key=>$val){
                switch ($val['status']){
                    case ShopProductModel::getStatus('wait_auth',1):
                        self::product_revoke($val,1,'待审核商品',$user_id,[],$param['revoke_remark']);
                        break;
                    case ShopProductModel::getStatus('auth_error',1):
                        self::product_revoke($val,1,'审核未通过商品',$user_id,[],$param['revoke_remark']);
                        break;
                    case ShopProductModel::getStatus('in',1):
                        //进行中
                        self::product_revoke($val,2,'进行中商品',$user_id,[],$param['revoke_remark']);
                        break;
                    case ShopProductModel::getStatus('success',1):
                        //完成
                        if(!isset($param['refund_type']) || count($param['refund_type'])<=0){
                            exception("请选择退款方式");
                        }
                        self::product_revoke($val,3,'完成商品',$user_id,$param['refund_type'],$param['revoke_remark']);
                        break;
                    case ShopProductModel::getStatus('stop',1):
                        //已暂停
                        self::product_revoke($val,4,'已暂停商品',$user_id,[],$param['revoke_remark']);
                        break;
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 商品撤销处理
     * @Author: 易军辉
     * @DateTime:2024-06-21 16:15
     * @param $val 商品信息
     * @param $type 撤销类型：1、直接根据商品信息退款   2、根据订单信息退款  3、完成订单撤销 4、暂停订单处理
     * @param $remark_prefix 备注前缀
     * @param $user_id 操作用户
     * @param $refund_type 退款方式：1、退商家本金 2、退商家佣金 3、扣买手本金 4、扣买手佣金
     * @param $revoke_remark 撤销原因
     */
    private static function product_revoke($val,$type=1,$remark_prefix='',$user_id=null,$refund_type=[],$revoke_remark=""){
        switch ($type){
            case 1:
                //待审核
                $consumption_res = MerchantService::refund(
                    $val['merchant_id'],
                    $val['money'],
                    $val['principal'],
                    $val['commission'],
                    '撤销商品退款',
                    $val['id'],
                    $val['merchant_shop_id'],
                    $remark_prefix."编号：".$val['id']
                );
                if($consumption_res){
                    $edit = Db::name('shop_product')->where('id',$val['id'])->update([
                        'status'=>ShopProductModel::getStatus('revoke',1),
                        'update_uid'=>$user_id,
                        'update_time'=>datetime(),
                    ]);
                }
                break;
            case 2:
                $order_list = Db::name('shop_order')
                    ->where('shop_product_id',$val['id'])
                    ->where('is_delete',0)
                    ->where('status','in',[
                        ShopOrderModel::getStatus('o_listing',1),
                        ShopOrderModel::getStatus('o_select',1),
                        ShopOrderModel::getStatus('o_taking',1),
                    ])
                    ->field('id,principal,mer_commission')
                    ->select()
                    ->toArray();
                if($order_list){
                    self::product_order_revoke($order_list,$val,$remark_prefix,$user_id,$revoke_remark);
                }
                break;
            case 3:
                //已完成的商品只能撤销已完成的订单
                $order_ids = Db::name('shop_order')
                    ->where('shop_product_id',$val['id'])
                    ->where('is_delete',0)
                    ->where('status','in',[
                        ShopOrderModel::getStatus('o_success',1)
                    ])
                    ->column('id');
                if($order_ids){
                    //退款
                    $param['refund_type'] = $refund_type;
                    $param['revoke_remark'] = $revoke_remark;
                    $param['ids'] = $order_ids;
                    $data = ShopOrderService::revoke($order_ids,$param);
                    //更改商品状态
                    $edit = Db::name('shop_product')->where('id',$val['id'])->update([
                        'status'=>ShopProductModel::getStatus('revoke',1),
                        'update_uid'=>$user_id,
                        'update_time'=>datetime(),
                        'revoke_remark'=>$revoke_remark,
                    ]);
                }
                break;
            case 4://暂停商品
                $order_list = Db::name('shop_order')
                    ->where('shop_product_id',$val['id'])
                    ->where('is_delete',0)
                    ->where('status','in',[
                        ShopOrderModel::getStatus('o_stop',1),
                    ])
                    ->where('old_status','in',[
                        ShopOrderModel::getStatus('o_listing',1),
                        ShopOrderModel::getStatus('o_select',1),
                        ShopOrderModel::getStatus('o_taking',1),
                    ])
                    ->field('id,principal,mer_commission')
                    ->select()
                    ->toArray();
                if($order_list){
                    self::product_order_revoke($order_list,$val,$remark_prefix,$user_id,$revoke_remark);
                }
                break;
        }
    }

    /**
     * 直接撤销未接单的订单进行退款
     * @Author: 易军辉
     * @DateTime:2024-09-25 18:06
     * @param $order_list 订单信息
     * @param $val 商品信息
     * @param $remark_prefix 备注前缀
     * @param $user_id 操作用户
     * @param $revoke_remark 撤销原因
     * @throws \think\db\exception\DbException
     */
    private static function product_order_revoke($order_list,$val,$remark_prefix,$user_id,$revoke_remark)
    {
        $principal = array_sum(array_column($order_list,'principal'));
        $mer_commission = array_sum(array_column($order_list,'mer_commission'));
        $consumption_res = MerchantService::refund(
            $val['merchant_id'],
            bcadd($principal,$mer_commission,2),
            $principal,
            $mer_commission,
            '撤销商品',
            $val['id'],
            $val['merchant_shop_id'],
            $remark_prefix."编号：".$val['id']."，撤销订单数：".count($order_list)
        );
        if($consumption_res){
            $order_edit = Db::name('shop_order')
                ->where('id','in',array_column($order_list,'id'))
                ->update([
                    'revoke_type'=>mer_user_id()>0?0:2,
                    'revoke_uid'=>$user_id,
                    'revoke_time'=>datetime(),
                    'status'=>ShopOrderModel::getStatus('o_revoke',1),
                    'revoke_remark'=>$revoke_remark,
                    'is_mer_principal'=>2,
                    'is_mer_commission'=>2,
                ]);
            $edit = Db::name('shop_product')->where('id',$val['id'])->update([
                'status'=>ShopProductModel::getStatus('revoke',1),
                'update_uid'=>$user_id,
                'update_time'=>datetime(),
                'revoke_remark'=>$revoke_remark,
            ]);
        }
        return true;
    }

    /**
     * 商品暂停
     * @Author: 易军辉
     * @DateTime:2024-06-20 19:27
     * @param $ids 商品IDS
     */
    public static function halt($ids)
    {
        Db::startTrans();
        try {
            $list = Db::name('shop_order')
                ->alias('a')
                ->leftJoin('shop_product','a.shop_product_id=shop_product.id')
                ->where('shop_product.id', 'in', $ids)
                ->where('shop_product.is_disable', 0)
                ->where('shop_product.is_delete', 0)
                ->where('shop_product.status', 'in',[
                    ShopProductModel::getStatus('in', 1)
                ])
                ->where('a.status', 'in',[
                    ShopOrderModel::getStatus('o_listing', 1),
                    ShopOrderModel::getStatus('o_select', 1),
                    ShopOrderModel::getStatus('o_taking', 1),
                ])
                ->where('a.is_delete', 0)
                ->field('a.id,a.shop_product_id,a.status')
                ->select()
                ->toArray();
            if(count($list)<=0){
                exception('未找到可以暂停的订单');
            }
            $shop_product_ids = array();
            foreach ($list as $key => $val) {
                $order_res = Db::name('shop_order')
                    ->where('id',$val['id'])
                    ->update([
                        'old_status'=>$val['status'],
                        'status'=>ShopOrderModel::getStatus('o_stop', 1),
                        'halt_uid'=>mer_user_id(),
                        'halt_time'=>date('Y-m-d H:i:s'),
                        'stop_remark'=>'商品管理手动暂停',
                        'update_uid'=>mer_user_id(),
                        'update_time'=>date('Y-m-d H:i:s'),
                    ]);
                if($order_res){
                    array_push($shop_product_ids,$val['shop_product_id']);
                }
            }
            if(array_unique($shop_product_ids)){
                $product_res = Db::name('shop_product')
                    ->where('id','in',array_unique($shop_product_ids))
                    ->update([
                        'old_status'=>ShopProductModel::getStatus('in', 1),
                        'status'=>ShopProductModel::getStatus('stop', 1),
                        'halt_uid'=>mer_user_id(),
                        'halt_time'=>date('Y-m-d H:i:s')
                    ]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }
    /**
     * 商品开启
     * @Author: 易军辉
     * @DateTime:2024-06-20 19:27
     * @param $ids 商品IDS
     */
    public static function open($ids)
    {
        Db::startTrans();
        try {
            $list = Db::name('shop_order')
                ->alias('a')
                ->leftJoin('shop_product','a.shop_product_id=shop_product.id')
                ->where('shop_product.id', 'in', $ids)
                ->where('shop_product.is_disable', 0)
                ->where('shop_product.is_delete', 0)
                ->where('shop_product.status', 'in',[
                    ShopProductModel::getStatus('stop', 1)
                ])
                ->where('a.status', 'in',[
                    ShopOrderModel::getStatus('o_stop', 1)
                ])
                ->where('a.old_status', 'in',[
                    ShopOrderModel::getStatus('o_listing', 1),
                    ShopOrderModel::getStatus('o_select', 1),
                    ShopOrderModel::getStatus('o_taking', 1),
                ])
                ->where('a.is_delete', 0)
                ->field('a.id,a.shop_product_id,a.status,a.stop_remark,a.old_status')
                ->select()
                ->toArray();
            if(count($list)<=0){
                exception('未找到可以开启的订单');
            }
            $shop_product_ids = array();
            foreach ($list as $key => $val) {
                $order_res = Db::name('shop_order')
                    ->where('id',$val['id'])
                    ->update([
                        'old_status'=>$val['status'],
                        'status'=>$val['old_status'],
                        'stop_remark'=>$val['stop_remark'].",已开启",
                        'update_uid'=>mer_user_id(),
                        'update_time'=>date('Y-m-d H:i:s'),
                    ]);
                if($order_res){
                    array_push($shop_product_ids,$val['shop_product_id']);
                }
            }
            if(array_unique($shop_product_ids)){
                $product_res = Db::name('shop_product')
                    ->where('id','in',array_unique($shop_product_ids))
                    ->update([
                        'old_status'=>ShopProductModel::getStatus('stop', 1),
                        'status'=>ShopProductModel::getStatus('in', 1),
                    ]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 商品表状态根据订单状态进行监听改变
     * @Author: 易军辉
     * @DateTime:2024-10-17 17:41
     * @param $shop_product_ids
     * @return boolean
     */
    public static function changeStatus($shop_product_ids=null)
    {
        if(!$shop_product_ids){
            return false;
        }
        if(!is_array($shop_product_ids)){
            $shop_product_ids=[$shop_product_ids];
        }
        $ids_str = implode(',',$shop_product_ids);
        $order_field =" shop_product_id";
        foreach (ShopOrderModel::STATUS as $k => $v) {
            if($order_field != ""){
                $order_field .=",";
            }
            $order_field .= ' COUNT(CASE WHEN status = '.$v['value'].' THEN 1 END) as '.$v['code'];
        }
        $status_in = ShopProductModel::getStatus('in',1);//进行中
        $status_revoke = ShopProductModel::getStatus('revoke',1);//撤销
        $status_success = ShopProductModel::getStatus('success',1);//完成
        $status_str = $status_in.",".
            $status_success.",".
            $status_revoke.",".
            ShopProductModel::getStatus('stop',1);
        $sql = <<<SQL
                SELECT 
                 a.id,
                 a.status,
                 a.old_status,
                 -- 统计全部订单数量
                (SELECT COUNT(o.id) 
                 FROM ya_shop_order AS o 
                 WHERE o.shop_product_id = a.id and o.is_delete =0 ) AS order_all,
                 orders.*
                FROM ya_shop_product AS a
                -- 关联订单
                LEFT JOIN(
                  SELECT 
                  {$order_field}
                  FROM ya_shop_order where is_delete=0 GROUP BY shop_product_id
                )as orders ON a.id = orders.shop_product_id
            WHERE
                a.is_delete = 0 
              and a.status in({$status_str})
              and a.id in ({$ids_str})
            ORDER BY 
                a.status asc,a.id desc
            SQL;
        $list = Db::query($sql);
        $change_num = 0;
        Db::startTrans();
        try {
            foreach ($list as $key=>$val){
                $status = $val['status'];
                $old_status = $val['old_status'];
                //若撤销订单数量大于0，则商品状态更改为撤销状态
                if(isset($val['o_revoke']) && $val['o_revoke']>0){
                    $status = $status_revoke;
                    $old_status =$val['status'];
                }else if(isset($val['o_success']) && $val['o_success']==$val['order_all']){//完成数量等于总数量
                    $status = $status_success;
                    $old_status =$val['status'];
                }
                $product_res = Db::name('shop_product')
                    ->where('id',$val['id'])
                    ->update([
                        'old_status'=>$old_status,
                        'status'=>$status,
                        'update_uid'=>operate_user_id(),
                        'update_time'=>date('Y-m-d H:i:s')
                    ]);
                if($product_res){
                    $change_num +=1;
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $change_num;
    }
    /**
     * 商品置顶
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function top($ids, $param = [])
    {
        $model = new ShopProductModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->whereIn('status',[
                ShopProductModel::getStatus('in',1),
                ShopProductModel::getStatus('revoke',1),
                ShopProductModel::getStatus('stop',1),
            ])
            ->where('shop_product_type_code','PTBT')
            ->where($pk, 'in', $ids)
            ->field("id,update_uid,is_top,top_time")
            ->select();
        if(count($list)<=0){
            exception("未有符合平台补贴条件的商品需要置顶");
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->top_time=datetime();
                $v->update_uid=user_id();
                $v->is_top=$param['is_top'];
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        ShopProductCache::del($ids);
        return $param;
    }

    /**
     * 查询平台补贴商品详情
     * @Author: 易军辉
     * @DateTime:2024-10-21 18:11
     * @param $id
     * @param $exce
     */
    public static function getSubsidiesInfo($id, $exce = true)
    {
        //查询语句
        $sql = self::getSubsidiesSql([['id','=',$id]],[],"");
        $list = Db::query($sql);
        if ($exce && count($list)<=0) {
            exception("该商品已被抢光，请换一个商品");
        }
        //查询图片路径
        foreach ($list as $key=>$item) {
            //商品主图
            $list[$key]['image_url'] = "";
            if(isset($item['image_id'])){
                $file = MerchantFileService::info($item['image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['image_url'] =$file['file_url'];
                }
            }
            //活动图片
            $list[$key]['activity_image_url'] = "";
            if(isset($item['activity_image_id'])){
                $file = MerchantFileService::info($item['activity_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['activity_image_url'] =$file['file_url'];
                }
            }
            //店铺图片
            $list[$key]['platform_image_url'] = "";
            if($item['platform_code'] == SettingStorePlatformModel::CODE_TM){
                $platform = SettingStorePlatformModel::getPlatform(SettingStorePlatformModel::CODE_TB,4);
                if($platform){
                    $list[$key]['platform_title'] =$platform['title'];
                    $file = FileService::info($platform['image_id']);
                    if($file && isset($file['file_url'])){
                        $list[$key]['platform_image_url'] =$file['file_url'];
                    }
                }
            }else if($item['platform_image_id']){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
            //商品详情
            if($item['content']){
                $content_files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$item['content']))
                    ->select()
                    ->toArray();
                $content_imgs = [];
                foreach ($content_files as $c_k=>$c_v){
                    $content_imgs[] = SettingService::fileUrl($c_v);
                }
                $list[$key]['content'] =$content_imgs;
            }else{
                $list[$key]['content'] =[];
            }
            //结束时间处理
            $end_date = new DateTime(); // 默认当前时间
            if($item['advertising_time']) {
                $end_date = new DateTime($item['advertising_time']);
            }
            // 添加结束小时数
            $end_date->modify('+'.(isset($item['e_revoke_time'])?$item['e_revoke_time']:0).' hours');
            // 获取当前时间的时间戳
            $current_time = new DateTime();
            $current_timestamp = $current_time->getTimestamp();

            // 获取结束时间的时间戳
            $end_timestamp = $end_date->getTimestamp();
            $list[$key]['time_diff_in_seconds'] =$end_timestamp - $current_timestamp;
            //商品分享标题处理
            $list[$key]['share_title'] = "";
            if(isset($item['order_price'])){
                $list[$key]['share_title'] .="【￥".$item['order_price']."元";
            }
            if(isset($item['goods_show_refund_price'])) {
                if ($list[$key]['share_title'] != "") {
                    $list[$key]['share_title'] .= ",平台补贴" . $item['goods_show_refund_price'] . "元";
                } else {
                    $list[$key]['share_title'] .= "【平台补贴" . $item['goods_show_refund_price'] . "元";
                }
            }
            if($list[$key]['share_title']!=""){
                $list[$key]['share_title'] .="】";
            }
            $list[$key]['share_title'] .= isset($item['activity_title'])?$item['activity_title']:'';
        }
        return $list[0];
    }
    /**
     * 查询垫付任务商品
     * @Author: 易军辉
     * @DateTime:2024-10-19 16:00
     * @param $param
     * @param $page
     * @param $limit
     * @param $order
     * @param $field
     * @return array
     */
    public static function getSubsidiesOrder($param = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        /*****************条件组装*******************/
        $where = [];
        //商品类目
        if(isset($param['setting_store_type_id']) && $param['setting_store_type_id']>0){
            $where[] = ['setting_store_type_id','=',$param['setting_store_type_id']];
        }
        //过滤商品id
        if(isset($param['id']) && $param['id']>0){
            $where[] = ['id','<>',$param['id']];
        }
        //商品名称搜索
        if(isset($param['keyword']) && $param['keyword']>0){
            $where[] = ['keyword','=',$param['keyword']];
        }
        //查询语句
        $sql = self::getSubsidiesSql($where,$order,$field);
        if ($page == 0 || $limit == 0) {
            return Db::query($sql);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        //查询图片路径
        foreach ($list as $key=>$item) {
            //商品主图
            $list[$key]['image_url'] = "";
            if(isset($item['image_id'])){
                $file = MerchantFileService::info($item['image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['image_url'] =$file['file_url'];
                }
            }
            //活动主图
            $list[$key]['activity_image_url'] = "";
            if(isset($item['activity_image_id'])){
                $file = MerchantFileService::info($item['activity_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['activity_image_url'] =$file['file_url'];
                }
            }
            //店铺图片
            $list[$key]['platform_image_url'] = "";
            if($item['platform_code'] == SettingStorePlatformModel::CODE_TM){
                $platform = SettingStorePlatformModel::getPlatform(SettingStorePlatformModel::CODE_TB,4);
                if($platform){
                    $list[$key]['platform_title'] =$platform['title'];
                    $file = FileService::info($platform['image_id']);
                    if($file && isset($file['file_url'])){
                        $list[$key]['platform_image_url'] =$file['file_url'];
                    }
                }
            }else if($item['platform_image_id']){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 查询平台补贴商品
     * @Author: 易军辉
     * @DateTime:2024-10-19 19:41
     * @param $where
     * @param $order
     * @param $field
     * @return string
     */
    private static function getSubsidiesSql($where = [], $order = [],$field = '')
    {
        $status_inventory = ShopOrderModel::getStatus('o_select',1).",".
            ShopOrderModel::getStatus('o_taking',1);
        $status_sales = ShopOrderModel::getStatus('o_operation',1).",".
            ShopOrderModel::getStatus('o_delivery',1).",".
            ShopOrderModel::getStatus('o_evaluate',1).",".
            ShopOrderModel::getStatus('o_auth',1).",".
            ShopOrderModel::getStatus('o_success',1).",".
            ShopOrderModel::getStatus('o_auth_error',1).",".
            ShopOrderModel::getStatus('o_stop',1);
        //已接单状态
        $status_str = ShopOrderModel::getStatus('o_delivery',1).","
            .ShopOrderModel::getStatus('o_evaluate',1).","
            .ShopOrderModel::getStatus('o_auth',1).","
            .ShopOrderModel::getStatus('o_success',1);
        /***************************查询字段***********************************************/
        if (empty($field)) {
            $field = "product.id,
                    product.is_top,
                    product.merchant_shop_id,
                    product.top_time,
                    product.e_revoke_time,
                    platform.title as platform_title,
                    platform.code as platform_code,
					platform.image_id as platform_image_id,
                    goods.image_id,
                    goods.activity_image_id,
                    goods.setting_store_type_id,
                    goods.goods_title,
                    goods.activity_title,
                    goods.order_price,
                    goods.activity_price,
                    goods.content,
                    -- 查询基础佣金
                    (SELECT sum(price.user_price) 
                     FROM ya_shop_product_price AS price 
                     WHERE price.shop_product_id = product.id and price.type='basic_price') AS basic_price,
                    -- 查询活动补贴金额
                    (SELECT sum(price.user_price) 
                     FROM ya_shop_product_price AS price 
                     WHERE price.shop_product_id = product.id and price.type='refund_principal') AS refund_principal_price,
                    -- 查询展示价格
                    (goods.activity_price-(SELECT sum(price.user_price) 
                     FROM ya_shop_product_price AS price 
                     WHERE price.shop_product_id = product.id and price.type='basic_price')) as goods_show_price,
                    -- 查询补贴价格
                    (
                        (SELECT sum(price.user_price) FROM ya_shop_product_price AS price WHERE price.shop_product_id = product.id and price.type='basic_price')
                        +
                        (SELECT sum(price.user_price) FROM ya_shop_product_price AS price WHERE price.shop_product_id = product.id and price.type='refund_principal')
                    )as goods_show_refund_price,
                    -- 查询第一个订单上架时间
                    (SELECT min(o.advertising_time) 
                     FROM ya_shop_order AS o 
                     WHERE o.shop_product_id = product.id  and o.is_delete =0 and o.status in (".$status_inventory.")
                         ) AS advertising_time,
                    -- 查询订单库存数量
                    (SELECT COUNT(o.id) 
                     FROM ya_shop_order AS o 
                     WHERE o.shop_product_id = product.id  and o.is_delete =0 and o.status in (".$status_inventory.")
                         ) AS order_num,
                    -- 查询订单销量
                    (SELECT COUNT(o.id) 
                     FROM ya_shop_order AS o 
                     WHERE o.shop_product_id in 
                     (SELECT shop_product_id from ya_shop_product_goods as o_goods where o_goods.third_id=goods.third_id GROUP BY shop_product_id)
                     and o.is_delete =0 and o.shop_product_type_code='PTBT' and o.status in (".$status_sales.")
                    ) AS order_sales,
                    -- 查询商品浏览量
                    (
                        SELECT sum(browse_num) from ya_shop_product_goods as o_goods where o_goods.third_id=goods.third_id
                    ) as browse_num ";
        }

        /***************************组装条件***********************************************/
        $where_sql = " a.id>0 ";
        foreach ($where as $key=>$val){
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if($val[0] == 'keyword'){
                $where_sql .=" (a.goods_title like '%".$val[2]."%' or a.activity_title like '%".$val[2]."%')";
            }else if(is_array($val[2])) {
                $where_sql .= "a." . $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else{
                $where_sql .="a.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
        /***************************组装排序***********************************************/
        $order_sql = "";
        foreach ($order as $key=>$val){
            if($order_sql!=""){
                $order_sql .=" , ";
            }
            $order_sql .="a.".$key." ".$val." ";
        }
        if($order_sql == ""){
            $order_sql = "a.is_top desc,a.top_time desc,a.goods_show_price asc,a.order_sales desc,a.browse_num desc";
        }
        /***************************店铺复购条件过滤***********************************************/
        $member_id = member_id();
        if($member_id>0){
            $shop_id_sql =<<<SQL
                        SELECT 
                        o.merchant_shop_id
                        from ya_shop_order as o
                        LEFT JOIN ya_merchant_shop as shop on o.merchant_shop_id = shop.id
                        where 
                        o.status in ({$status_str})
                        and shop.repurchase_days>0
                        and DATEDIFF(NOW(), o.meet_time)<shop.repurchase_days
                        and o.member_id ={$member_id}
            SQL;
            $shop_list = Db::query($shop_id_sql);
            if(count($shop_list)>0){
                $where_sql .=" and a.merchant_shop_id not in (".implode(',',array_unique(array_column($shop_list,'merchant_shop_id'))).")";
            }
        }
//        echo $where_sql;exit();
        $sql = <<<SQL
            SELECT * from (
                SELECT 
                {$field}
                from ya_shop_product_goods as goods
                LEFT JOIN ya_shop_product as product on product.id = goods.shop_product_id
                LEFT JOIN ya_setting_store_platform as platform on platform.id=product.store_platform_id
                where 
                product.is_disable = 0
                and product.is_delete = 0
                and product.shop_product_type_code = 'PTBT'
                and 
                -- 订单库存数量大于0
                (SELECT COUNT(o.id) 
                 FROM ya_shop_order AS o 
                 WHERE o.shop_product_id = product.id  and o.is_delete =0 and o.status in ({$status_inventory})
                     )>0
            ) as a
            WHERE
                {$where_sql}
            ORDER BY 
                {$order_sql}
        SQL;
        return $sql;
    }

    /**
     * 商品海报生成
     * @Author: 易军辉
     * @DateTime:2024-11-21 14:50
     * @param $param
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createPoster($param)
    {
        $qr_code_utils = new QrCodeUtils();
        $qr_code_url = "";//二维码
        $scene = "";//商品参数
        /***********************************页面路径**********************************/
        $page = "pages/app/home";
        switch ($param['goods_type']){
            case 1://淘宝联盟
                $page = "pages/goods/tblm_details";
                break;
            case 2://补贴商品
                $page = "pages/goods/subsidy_details";
                break;
        }
        /***********************************跳转参数**********************************/
        if(isset($param['field_name']) && isset($param['field_value'])){
            if($param['platform'] == 'wechat'){
                $scene .=$param['field_name']."=123";
            }else{
                $scene .=$param['field_name']."=".$param['field_value'];
            }
        }
        //邀请码
        $invitation_code = "";
        $member_id = member_id();
        if($member_id>0){
            $invitation_code = Db::name('member')
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->where('member_id',$member_id)
                ->value('invitation_code');
        }
        if($invitation_code){
            if($scene!=""){
                $scene .="&";
            }
            $scene .="in_code=".$invitation_code;
        }
        /***********************************生成二维码**********************************/
        $member_setting = MemberSettingService::info('member_name,logo_id,wx_miniapp_appid,wx_miniapp_appsecret');
        switch ($param['platform']){
            case 'wechat':
                if(!$member_setting['wx_miniapp_appid'] || !$member_setting['wx_miniapp_appsecret']){
                    error('请联系平台配置微信参数');
                }
                $miniapp     = new \thirdsdk\WxMiniapp($member_setting['wx_miniapp_appid'], $member_setting['wx_miniapp_appsecret']);
                $qr_code_url   = $miniapp->getWechatQRCode($scene,$page,180);
                break;
            case 'routine':
                $sysSetting = SystemSettingService::info('member_website');
                $register_url = $sysSetting['member_website']."/".$page.'?'.$scene;
                //生成二维码
                $qr_code_url = $qr_code_utils->generateQrCodeUrl($register_url,180,"poster_code_".$invitation_code,false);
                break;
        }
        /***********************************生成海报**********************************/
        $param['background_path'] = 'storage/app/posterbackgd.png';//背景图
        $param['qr_code_url'] = $qr_code_url;//邀请二维码：storage/file/20241121/poster_code_RFXXAUJ.png
        $param['key'] = $scene;//缓存名称
        $param['invitation_code'] = $invitation_code;//邀请码
        $param['member_name'] = $member_setting['member_name'];//移动端名称
        $param['logo_url'] ="";//logo
        if(isset($member_setting['logo_id'])){
            $logo_image = FileService::info($member_setting['logo_id']);
            $param['logo_url'] =isset($logo_image['file_path'])?$logo_image['file_path']:'';
        }
        $poster_url = $qr_code_utils->createGoodsPoster($param);
        return file_url($poster_url);
    }
}
